package com.sansui.blog.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.sansui.blog.pojo.*;
import com.sansui.blog.pojo.vo.BlogInfoQuery;
import com.sansui.blog.service.*;
import com.sansui.blog.utils.IpUtil;
import com.sansui.blog.utils.JsonUtil;
import com.sansui.blog.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @name: IndexController
 * @author: Sansui
 * @Software: IDEA
 * @Blog: https://www.cnblogs.com/sansui6/
 * @date: 2022-04-17 22:13
 **/
@RestController
public class BlogIndexController {

    @Autowired
    private BlogService blogService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private TagService tagService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private SysInfoService sysInfoService;

    @Value("${blog.qqInfo-api}")
    private String qqInfoApi;

    @GetMapping(value = {"/index","/"})
    public ModelAndView blogIndex(@RequestParam(value = "pageNum",required = false,defaultValue = "1")String page,
                                  @RequestParam(value = "pageSize",required = false,defaultValue = "5")Integer pageSize,
                                  ModelAndView mv){
        if(!StringUtils.isNumeric(page)){
            mv.setViewName("/error/404");
            return mv;
        }
        Integer pageNum = Integer.valueOf(page);
        PageInfo <BlogInfoQuery> pageInfo = blogService.queryAllByPage(pageNum,pageSize,null,null,null);
        List<Map<String, Object>> typeInfo = typeService.countTypeInfo(1);
        List<Tag> tagInfo = tagService.findAll();
        List<Blog> blogInfo = blogService.getRecommendedBlog();
        SysConfig sysConfig = sysInfoService.getSysSetting();
        mv.setViewName("theme/"+ sysConfig.getThemeName() +"/index");
        mv.addObject("webname",sysConfig.getWebname());
        mv.addObject("webTitle",sysConfig.getWebTitle());
        mv.addObject("pageInfo",pageInfo);
        mv.addObject("types",typeInfo);
        mv.addObject("tags",tagInfo);
        mv.addObject("recommendedBlogs",blogInfo);
        return mv;
    }

    @GetMapping(value = {"/search"})
    public ModelAndView blogIndexSearch(@RequestParam(value = "pageNum",required = false,defaultValue = "1")String page,
                                  @RequestParam(value = "pageSize",required = false,defaultValue = "5")Integer pageSize,
                                  @RequestParam String keyword,
                                  ModelAndView mv){

        if(!StringUtils.isNumeric(page)){
            mv.setViewName("/error/404");
            return mv;
        }
        Integer pageNum = Integer.valueOf(page);

        PageInfo <BlogInfoQuery> pageInfo = blogService.queryAllByPage(pageNum,pageSize,null,null,keyword);
        List<Map<String, Object>> typeInfo = typeService.countTypeInfo(1);
        List<Tag> tagInfo = tagService.findAll();
        List<Blog> blogInfo = blogService.getRecommendedBlog();
        SysConfig sysConfig = sysInfoService.getSysSetting();

        Map<String, Object> searchInfo = new HashMap<>(16);
        searchInfo.put("keyword",keyword);
        searchInfo.put("total",pageInfo.getTotal());

        mv.setViewName("theme/"+ sysConfig.getThemeName() +"/search");
        mv.addObject("pageInfo",pageInfo);
        mv.addObject("types",typeInfo);
        mv.addObject("tags",tagInfo);
        mv.addObject("recommendedBlogs",blogInfo);
        mv.addObject("searchInfo",searchInfo);
        mv.addObject("webname",sysConfig.getWebname());
        return mv;
    }


    @GetMapping("/blogs/{id}")
    public ModelAndView blog(@PathVariable String id, ModelAndView mv, HttpSession session,HttpServletRequest request) {

        if(!StringUtils.isNumeric(id)){
            mv.setViewName("/error/404");
            return mv;
        }
        Long blogId = Long.valueOf(id);

        Blog blog = blogService.getAndConvert(blogId);

        if(blog == null){
            mv.setViewName("/error/404");
            return mv;
        }

        //过滤 状态无效博客信息 前台查询
        if(blog.getStatus()!=1){
            mv.setViewName("/error/404");
            return mv;
        }

        doGet(session,request,blogId);

//        User user = (User) session.getAttribute("user");
        Map<String,Object> data = (Map<String, Object>) session.getAttribute("user");

        if (data != null) {
            UserInfo userInfo = userInfoService.getUserInfoByUserId(String.valueOf(data.get("uid")));
            userInfo.setPhone(null);
            userInfo.setRegisterIp(null);
            userInfo.setUpdateTime(null);
            userInfo.setCreateTime(null);
            userInfo.setUid(null);
            mv.addObject("userInfo", userInfo);
        }
        SysConfig sysConfig = sysInfoService.getSysSetting();
        mv.setViewName("theme/"+ sysConfig.getThemeName() +"/blog");
        mv.addObject("webname",sysConfig.getWebname());
        mv.addObject("blog", blog);
        mv.addObject("blogs", blogService.getBogPageChange(blogId));
        return mv;
    }

    @PostMapping("/blogs/getAvatar")
    public Map<String, Object> getAvatar(String qq, ModelAndView mv)throws Exception {
        String qqApi = qqInfoApi+qq;
        JSONObject jsonObject = JsonUtil.loadJson(qqApi);
        Map<String, Object> map = new HashMap<>(16);
        Boolean success = ((Boolean)jsonObject.get("success")).booleanValue();
        if(!success){
            map.put("code",400);
            return map;
        }
        map.put("code",200);
        map.put("data",jsonObject);
        return map;
    }

    public void doGet(HttpSession session,HttpServletRequest request,Long blogId){

        Integer count = (Integer) session.getAttribute("count");
        String ipAddress = IpUtil.getIpAddr(request);
        if (count == null) {
            count = 1;
            blogService.updateBlogViews(blogId);
        } else {
            if (session.getAttribute("ip") != null && !session.getAttribute("ip").equals(ipAddress)) {
                count = new Integer(count.intValue()) + 1;
                blogService.updateBlogViews(blogId);
            }else if(blogId != (Long) session.getAttribute("blogId")){
                count = new Integer(count.intValue()) + 1;
                blogService.updateBlogViews(blogId);
            }
        }
        //设置属性,将count保存到当前的上下文中
        session.setAttribute("count", count);
        session.setAttribute("blogId", blogId);
        session.setAttribute("ip", ipAddress);
    }

}
